package core.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static core.Constants.Mq.*;

@Configuration
public class RabbitInitConfig {
    //与rabbit连接工厂的名字不一样，
    // 否则可能spring容器中有同名的对象，会导致注入错误的问题
    @Bean
    public CachingConnectionFactory rabbitConnectionFactory() {
        return new CachingConnectionFactory("localhost");
    }

    @Bean
    public RabbitAdmin amqpAdmin() {
        return new RabbitAdmin(rabbitConnectionFactory());
    }

    @Bean
    public Exchange exchange() {
        return ExchangeBuilder
                .topicExchange(EXCHANGE_NAME).build();
    }

    @Bean
    public Queue myQueue() {
        return QueueBuilder.durable(QUEUE_PRODUCT).build();
    }

    @Bean
    public Binding binding() {
        return BindingBuilder
                .bind(myQueue())
                .to(exchange())
                .with(ROUTING_KEY)
                .noargs();
    }

    //============================init================
    @Bean
    public Queue myQueueInit() {
        return QueueBuilder.durable(QUEUE_INIT).build();
    }

    @Bean
    public Binding bindingInit() {
        return BindingBuilder
                .bind(myQueueInit())
                .to(exchange())
                .with(ROUTING_KEY_INIT)
                .noargs();
    }
}